/**
 * 蓝牙连接管理器
 * 
 * 负责管理蓝牙连接的核心类，提供以下功能：
 * 1. 蓝牙适配器初始化和状态检查
 * 2. 设备扫描和发现
 * 3. 设备连接和断开
 * 4. 连接状态监听
 * 
 * 使用方法：
 * - 通过getInstance()获取单例实例
 * - 使用StateFlow监听连接状态变化
 * - 调用connectToDevice()连接设备
 * 
 * 原理：
 * - 使用单例模式确保全局唯一实例
 * - 利用StateFlow提供响应式状态管理
 * - 通过协程处理异步蓝牙操作
 */
package com.example.brain_wave.bluetooth

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.ActivityCompat
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import timber.log.Timber
import java.io.IOException
import java.util.*

/**
 * 蓝牙管理器类
 * 使用单例模式，管理蓝牙连接的生命周期
 */
class BluetoothManager private constructor(private val context: Context) {
    
    companion object {
        @Volatile
        private var INSTANCE: BluetoothManager? = null
        
        /**
         * 获取蓝牙管理器实例
         */
        fun getInstance(context: Context): BluetoothManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: BluetoothManager(context).also { INSTANCE = it }
            }
        }
        
        /**
         * 重置实例（仅用于测试）
         */
        fun resetInstance() {
            synchronized(this) {
                INSTANCE = null
            }
        }
        
        // NeuroSky设备的UUID
        private val NEUROSKY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
    }

    private val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as android.bluetooth.BluetoothManager
    private val bluetoothAdapter: BluetoothAdapter? = bluetoothManager.adapter
    
    // 连接状态管理
    private val _connectionState = MutableStateFlow<BluetoothConnectionState>(BluetoothConnectionState.Disconnected)
    val connectionState: StateFlow<BluetoothConnectionState> = _connectionState.asStateFlow()
    
    // 发现的设备列表
    private val _discoveredDevices = MutableStateFlow<List<BluetoothDevice>>(emptyList())
    val discoveredDevices: StateFlow<List<BluetoothDevice>> = _discoveredDevices.asStateFlow()
    
    // 当前连接的Socket
    private var currentSocket: BluetoothSocket? = null
    
    // 协程作用域
    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    
    init {
        Timber.plant(Timber.DebugTree())
        Timber.d("BluetoothManager initialized")
    }
    
    /**
     * 检查蓝牙是否可用
     */
    fun isBluetoothAvailable(): Boolean {
        return bluetoothAdapter != null
    }
    
    /**
     * 检查蓝牙是否已启用
     */
    fun isBluetoothEnabled(): Boolean {
        return bluetoothAdapter?.isEnabled == true
    }
    
    /**
     * 检查是否有必要的蓝牙权限
     */
    fun hasBluetoothPermissions(): Boolean {
        val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            arrayOf(
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_CONNECT,
                Manifest.permission.ACCESS_FINE_LOCATION
            )
        } else {
            arrayOf(
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.ACCESS_FINE_LOCATION
            )
        }
        
        return permissions.all { permission ->
            ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
        }
    }
    
    /**
     * 启用蓝牙（需要用户确认）
     * 注意：从Android 10开始，应用无法直接启用蓝牙，需要用户手动操作
     */
    fun enableBluetooth() {
        if (!isBluetoothEnabled()) {
            Timber.d("Bluetooth is not enabled. User needs to enable it manually.")
            // 在实际应用中，这里应该启动一个Intent让用户启用蓝牙
            // 但在这个简化版本中，我们只记录日志
        } else {
            Timber.d("Bluetooth is already enabled")
        }
    }
    
    /**
     * 获取已配对的设备列表
     */
    fun getPairedDevices(): List<BluetoothDevice> {
        if (!hasBluetoothPermissions()) {
            Timber.w("Missing bluetooth permissions")
            return emptyList()
        }
        
        return try {
            bluetoothAdapter?.bondedDevices?.toList() ?: emptyList()
        } catch (e: SecurityException) {
            Timber.e(e, "Security exception when getting paired devices")
            emptyList()
        }
    }
    
    /**
     * 查找NeuroSky设备
     * 在已配对设备中查找NeuroSky相关设备
     */
    fun findNeuroSkyDevices(): List<BluetoothDevice> {
        return getPairedDevices().filter { device ->
            try {
                val deviceName = device.name?.lowercase() ?: ""
                deviceName.contains("neurosky") || 
                deviceName.contains("mindwave") ||
                deviceName.contains("mw") ||
                device.address.startsWith("00:13:EF") // NeuroSky的MAC地址前缀
            } catch (e: SecurityException) {
                Timber.e(e, "Security exception when checking device name")
                false
            }
        }
    }

    /**
     * 开始扫描蓝牙设备
     */
    fun startScanning() {
        if (!hasBluetoothPermissions()) {
            Timber.w("Cannot start scanning: missing Bluetooth permissions")
            return
        }
        
        if (!isBluetoothEnabled()) {
            Timber.w("Cannot start scanning: Bluetooth is not enabled")
            return
        }
        
        try {
            bluetoothAdapter?.startDiscovery()
            Timber.d("Started Bluetooth device discovery")
        } catch (e: SecurityException) {
            Timber.e(e, "Security exception when starting discovery")
        }
    }

    /**
     * 停止扫描蓝牙设备
     */
    fun stopScanning() {
        try {
            bluetoothAdapter?.cancelDiscovery()
            Timber.d("Stopped Bluetooth device discovery")
        } catch (e: SecurityException) {
            Timber.e(e, "Security exception when stopping discovery")
        }
    }
    
    /**
     * 连接到指定的蓝牙设备
     */
    fun connectToDevice(device: BluetoothDevice) {
        if (!hasBluetoothPermissions()) {
            _connectionState.value = BluetoothConnectionState.Failed("缺少蓝牙权限")
            return
        }
        
        scope.launch {
            try {
                val deviceName = device.name ?: "Unknown Device"
                _connectionState.value = BluetoothConnectionState.Connecting(deviceName)
                Timber.d("Attempting to connect to device: $deviceName")
                
                // 创建蓝牙Socket
                val socket = device.createRfcommSocketToServiceRecord(NEUROSKY_UUID)
                
                // 停止设备发现以提高连接性能
                bluetoothAdapter?.cancelDiscovery()
                
                // 连接设备
                socket.connect()
                
                currentSocket = socket
                _connectionState.value = BluetoothConnectionState.Connected(deviceName, device.address)
                Timber.i("Successfully connected to device: $deviceName")
                
            } catch (e: IOException) {
                Timber.e(e, "Failed to connect to device")
                _connectionState.value = BluetoothConnectionState.Failed("连接失败: ${e.message}")
                currentSocket?.close()
                currentSocket = null
            } catch (e: SecurityException) {
                Timber.e(e, "Security exception during connection")
                _connectionState.value = BluetoothConnectionState.Failed("权限错误: ${e.message}")
            }
        }
    }
    
    /**
     * 断开当前连接
     */
    fun disconnect() {
        scope.launch {
            try {
                currentSocket?.close()
                currentSocket = null
                _connectionState.value = BluetoothConnectionState.Disconnected
                Timber.i("Bluetooth connection disconnected")
            } catch (e: IOException) {
                Timber.e(e, "Error during disconnect")
            }
        }
    }
    
    /**
     * 检查当前是否已连接
     */
    fun isConnected(): Boolean {
        return currentSocket?.isConnected == true
    }
    
    /**
     * 获取当前连接的Socket（用于数据传输）
     */
    fun getCurrentSocket(): BluetoothSocket? {
        return currentSocket
    }
    
    /**
     * 清理资源
     */
    fun cleanup() {
        scope.cancel()
        disconnect()
        Timber.d("BluetoothManager cleaned up")
    }
}